/**
 * 通用工具函数
 */

/**
 * 格式化价格
 * @param {Number|String} price 价格
 * @param {Number} decimals 小数位数
 * @param {String} symbol 货币符号
 * @returns {String} 格式化后的价格
 */
export const formatPrice = (price, decimals = 2, symbol = '¥') => {
  if (!price && price !== 0) return `${symbol}0.00`;
  
  const num = parseFloat(price);
  if (isNaN(num)) return `${symbol}0.00`;
  
  return `${symbol}${num.toFixed(decimals)}`;
};

/**
 * 防抖函数
 * @param {Function} fn 需要防抖的函数
 * @param {Number} delay 延迟时间（毫秒）
 * @returns {Function} 防抖后的函数
 */
export const debounce = (fn, delay = 300) => {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

/**
 * 节流函数
 * @param {Function} fn 需要节流的函数
 * @param {Number} delay 延迟时间（毫秒）
 * @returns {Function} 节流后的函数
 */
export const throttle = (fn, delay = 300) => {
  let lastTime = 0;
  return function (...args) {
    const nowTime = Date.now();
    if (nowTime - lastTime > delay) {
      fn.apply(this, args);
      lastTime = nowTime;
    }
  };
};

/**
 * 日期格式化
 * @param {Date|String|Number} date 日期对象/字符串/时间戳
 * @param {String} format 格式化字符串，如 'YYYY-MM-DD HH:mm:ss'
 * @returns {String} 格式化后的日期字符串
 */
export const formatDate = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
  if (!date) return '';
  
  let dt = date;
  if (typeof date === 'string' || typeof date === 'number') {
    dt = new Date(date);
  }
  
  if (!(dt instanceof Date) || isNaN(dt.getTime())) {
    return '';
  }
  
  const year = dt.getFullYear();
  const month = dt.getMonth() + 1;
  const day = dt.getDate();
  const hour = dt.getHours();
  const minute = dt.getMinutes();
  const second = dt.getSeconds();
  
  const padZero = (num) => String(num).padStart(2, '0');
  
  return format
    .replace(/YYYY/g, year)
    .replace(/MM/g, padZero(month))
    .replace(/DD/g, padZero(day))
    .replace(/HH/g, padZero(hour))
    .replace(/mm/g, padZero(minute))
    .replace(/ss/g, padZero(second));
};

/**
 * 深拷贝
 * @param {Object|Array} obj 需要深拷贝的对象或数组
 * @returns {Object|Array} 深拷贝后的对象或数组
 */
export const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') return obj;
  
  const clone = Array.isArray(obj) ? [] : {};
  
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      clone[key] = deepClone(obj[key]);
    }
  }
  
  return clone;
};

/**
 * 对象转查询字符串
 * @param {Object} params 参数对象
 * @returns {String} 查询字符串
 */
export const objectToQueryString = (params) => {
  if (!params || typeof params !== 'object') return '';
  
  return Object.entries(params)
    .filter(([_, value]) => value !== undefined && value !== null && value !== '')
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    .join('&');
};

/**
 * 查询字符串转对象
 * @param {String} queryString 查询字符串
 * @returns {Object} 参数对象
 */
export const queryStringToObject = (queryString) => {
  if (!queryString) return {};
  
  const params = {};
  const urlParams = new URLSearchParams(queryString.startsWith('?') ? queryString.substring(1) : queryString);
  
  for (const [key, value] of urlParams.entries()) {
    params[key] = value;
  }
  
  return params;
};

/**
 * 获取当前页面URL参数
 * @returns {Object} URL参数对象
 */
export const getPageQuery = () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  return currentPage.options || {};
};

/**
 * 随机生成UUID
 * @returns {String} UUID
 */
export const generateUUID = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}; 